<template>
  <div class="consultation-record-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">就诊记录管理</h1>
    </div>

    <!-- 筛选区域 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-select v-model="status" placeholder="就诊状态">
            <el-option label="全部" value="" />
            <el-option label="待就诊" value="pending" />
            <el-option label="就诊中" value="processing" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-select v-model="department" placeholder="就诊科室" :loading="!departmentList.length">
            <el-option label="全部" value="" />
            <el-option-group
                v-for="parentDept in departmentList"
                :key="parentDept.dept_id"
                :label="parentDept.name"
            >
              <el-option
                  v-for="childDept in parentDept.children"
                  :key="childDept.dept_id"
                  :label="childDept.name"
                  :value="childDept.name"
              />
            </el-option-group>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              placeholder="选择就诊日期范围"
              style="width: 100%"
              @change="handleSearch"
          />
        </el-col>
        <el-col :span="6">
          <el-input
              v-model="searchKey"
              placeholder="搜索患者姓名/挂号单号/诊断结果"
              clearable
          >
            <template #append>
              <el-button icon="Search" @click="handleSearch" />
            </template>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button @click="resetFilter">重置筛选</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 就诊记录列表 -->
    <el-card class="record-list-card">
      <el-table
          :data="filteredRecords"
          border
          style="width: 100%"
          @row-click="handleRowClick"
          :row-class-name="tableRowClassName"
          v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="序号" width="80" />
        <el-table-column prop="patientName" label="患者姓名" />
        <el-table-column prop="gender" label="性别" width="80" />
        <el-table-column prop="age" label="年龄" width="80" />
        <el-table-column prop="registrationNo" label="挂号单号" />
        <el-table-column prop="department" label="就诊科室" />
        <el-table-column prop="visitTime" label="就诊时间" />
        <el-table-column prop="doctorName" label="接诊医生" />
        <el-table-column prop="diagnosis" label="诊断结果" :show-overflow-tooltip="true" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag
                :type="
                 scope.row.status === 'pending' ? 'info' :
                 scope.row.status === 'processing' ? 'warning' :
                 scope.row.status === 'completed' ? 'success' : 'info'
               "
            >
              {{
                scope.row.status === 'pending' ? '待就诊' :
                    scope.row.status === 'processing' ? '就诊中' :
                        scope.row.status === 'completed' ? '已完成' : '待就诊'
              }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button
                size="small"
                type="primary"
                @click="handleViewDetails(scope.row)"
            >
              查看详情
            </el-button>
            <el-button
                size="small"
                type="text"
                @click="handleEditRecord(scope.row)"
                :disabled="scope.row.status === 'completed' || scope.row.status === 'cancelled'"
            >
              编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        />
      </div>
    </el-card>

    <!-- 就诊记录详情对话框 -->
    <el-dialog
        v-model="detailDialogVisible"
        title="就诊记录详情"
        :width="1000"
        :before-close="handleDialogClose"
    >
      <el-row :gutter="20">
        <!-- 患者基本信息 -->
        <el-col :span="24">
          <el-card class="patient-basic-card">
            <div class="patient-avatar-container">
              <div class="patient-avatar">
                <el-avatar :size="60">
                  <User />
                </el-avatar>
                <div class="patient-tag" v-if="currentRecord.order_status === 4">
                  <el-tag type="warning">就诊中</el-tag>
                </div>
              </div>

              <div class="patient-main-info">
                <div class="name-and-id">
                  <h3 class="patient-name">{{ currentRecord.patientName || '-' }}</h3>
                  <span class="patient-id">ID: {{ currentRecord.patientId || '-' }}</span>
                </div>

                <div class="patient-basic-details">
                  <div class="detail-item">
                    <span class="detail-label">性别：</span>
                    <span class="detail-value">{{ currentRecord.gender === 1 ? '男' : currentRecord.gender === 0 ? '女' : '-' }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">年龄：</span>
                    <span class="detail-value">{{ currentRecord.age || '-' }}岁</span>
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">出生日期：</span>
                    <span class="detail-value">{{ currentRecord.birth_date || '-' }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">联系电话：</span>
                    <span class="detail-value">{{ currentRecord.phone || '-' }}</span>
                  </div>
                  <div class="detail-item">
                    <span class="detail-label">身份证号：</span>
                    <span class="detail-value">{{ maskIdCard(currentRecord.id_card) || '-' }}</span>
                  </div>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 详细内容标签页 -->
      <el-tabs type="card" class="detail-tabs" v-model="activeTab">
        <!-- 就诊基本信息 -->
        <el-tab-pane label="就诊信息" name="visit-info">
          <el-card>
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="visit-info-item">
                  <span class="info-label">挂号单号：</span>
                  <span class="info-value">{{ currentRecord.registrationNo || '-' }}</span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">就诊科室：</span>
                  <span class="info-value">{{ formatDepartment(currentRecord.department) || '-' }}</span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">接诊医生：</span>
                  <span class="info-value">{{ currentRecord.doctorName || '-' }}</span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">就诊时间：</span>
                  <span class="info-value">{{ currentRecord.visitTime || '-' }}</span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">就诊状态：</span>
                  <span class="info-value">
                     <el-tag
                         :type="
                         currentRecord.order_status === 1 ? 'info' :
                         currentRecord.order_status === 4 ? 'warning' :
                         currentRecord.order_status === 3 ? 'success' : 'info'
                       "
                     >
                       {{
                         currentRecord.order_status === 1 ? '待就诊' :
                             currentRecord.order_status === 4 ? '就诊中' :
                                 currentRecord.order_status === 3 ? '已完成' : '待就诊'
                       }}
                     </el-tag>
                   </span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">症状描述：</span>
                  <span class="info-value">{{ currentRecord.symptoms || '-' }}</span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">就诊号：</span>
                  <span class="info-value">{{ currentRecord.visit_no || '-' }}</span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">就诊费用：</span>
                  <span class="info-value">{{ currentRecord.amount ? '¥' + currentRecord.amount : '-' }}</span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">关系：</span>
                  <span class="info-value">{{ currentRecord.relationship || '-' }}</span>
                </div>
              </el-col>

              <el-col :span="12">
                <div class="visit-info-item">
                  <span class="info-label">支付状态：</span>
                  <span class="info-value">
                     <el-tag :type="currentRecord.pay_status === 1 ? 'success' : 'warning'">
                       {{ currentRecord.pay_status === 1 ? '已支付' : '未支付' }}
                     </el-tag>
                   </span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">支付时间：</span>
                  <span class="info-value">{{ currentRecord.pay_time ? formatDateTime(currentRecord.pay_time) : '-' }}</span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">取消时间：</span>
                  <span class="info-value">{{ currentRecord.cancel_time ? formatDateTime(currentRecord.cancel_time) : '-' }}</span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">创建时间：</span>
                  <span class="info-value">{{ currentRecord.create_time ? formatDateTime(currentRecord.create_time) : '-' }}</span>
                </div>
                <div class="visit-info-item">
                  <span class="info-label">更新时间：</span>
                  <span class="info-value">{{ currentRecord.update_time ? formatDateTime(currentRecord.update_time) : '-' }}</span>
                </div>

              </el-col>
            </el-row>
          </el-card>

          <el-card class="mt-4">
            <template #header>
              <span>病情诊断</span>
              <el-button
                  size="small"
                  type="text"
                  @click="handleEditDiagnosis"
                  v-if="currentRecord.order_status !== 3"
              >
                编辑
              </el-button>
            </template>



            <!-- 病情诊断显示 -->
            <div v-if="!editDiagnosis" class="diagnosis-display">
              <div class="diagnosis-item">
                <span class="diagnosis-label">主诉：</span>
                <div class="diagnosis-content">{{ currentRecord.medicalRecord?.chief_complaint || '暂无主诉' }}</div>
              </div>
              <div class="diagnosis-item">
                <span class="diagnosis-label">现病史：</span>
                <div class="diagnosis-content">{{ currentRecord.medicalRecord?.present_illness || '暂无现病史' }}</div>
              </div>
              <div class="diagnosis-item">
                <span class="diagnosis-label">体格检查：</span>
                <div class="diagnosis-content">{{ currentRecord.medicalRecord?.physical_exam || '暂无体格检查结果' }}</div>
              </div>
              <div class="diagnosis-item">
                <span class="diagnosis-label">辅助检查：</span>
                <div class="diagnosis-content">{{ currentRecord.medicalRecord?.auxiliary_exam || '暂无辅助检查结果' }}</div>
              </div>
              <div class="diagnosis-item">
                <span class="diagnosis-label">诊断结果：</span>
                <div class="diagnosis-content">{{ currentRecord.medicalRecord?.diagnosis || '暂无诊断结果' }}</div>
              </div>
              <div class="diagnosis-item">
                <span class="diagnosis-label">治疗方案：</span>
                <div class="diagnosis-content">{{ currentRecord.medicalRecord?.treatment_plan || '暂无治疗方案' }}</div>
              </div>
            </div>

            <!-- 病情诊断编辑表单 -->
            <el-form v-if="editDiagnosis && diagnosisForm" ref="diagnosisFormRef" :model="diagnosisForm" label-width="100px">
              <el-form-item label="主诉：">
                <el-input
                    v-model="diagnosisForm.chiefComplaint"
                    type="textarea"
                    rows="2"
                    placeholder="请输入患者主诉..."
                />
              </el-form-item>
              <el-form-item label="现病史：">
                <el-input
                    v-model="diagnosisForm.presentIllness"
                    type="textarea"
                    rows="3"
                    placeholder="请输入现病史..."
                />
              </el-form-item>
              <el-form-item label="体格检查：">
                <el-input
                    v-model="diagnosisForm.physicalExam"
                    type="textarea"
                    rows="3"
                    placeholder="请输入体格检查结果..."
                />
              </el-form-item>
              <el-form-item label="辅助检查：">
                <el-input
                    v-model="diagnosisForm.auxiliaryExam"
                    type="textarea"
                    rows="3"
                    placeholder="请输入辅助检查结果..."
                />
              </el-form-item>
              <el-form-item label="诊断结果：">
                <el-input
                    v-model="diagnosisForm.diagnosis"
                    type="textarea"
                    rows="2"
                    placeholder="请输入诊断结果..."
                />
              </el-form-item>
              <el-form-item label="治疗方案：">
                <el-input
                    v-model="diagnosisForm.treatmentPlan"
                    type="textarea"
                    rows="3"
                    placeholder="请输入治疗方案..."
                />
              </el-form-item>

              <div class="form-actions">
                <el-button @click="editDiagnosis = false">取消</el-button>
                <el-button type="primary" @click="saveDiagnosis">保存</el-button>
              </div>
            </el-form>
          </el-card>
        </el-tab-pane>

        <!-- 医嘱信息 -->
        <el-tab-pane label="医嘱" name="medical-advice">
          <el-card>
            <template #header>
              <span>医嘱信息</span>
              <el-button
                  size="small"
                  type="text"
                  @click="showAddAdviceDialog = true"
                  v-if="(!currentRecord.medicalAdvice || !currentRecord.medicalAdvice.content) && currentRecord.order_status !== 3"
              >
                添加医嘱
              </el-button>
            </template>

            <div v-if="!currentRecord.medicalAdvice || !currentRecord.medicalAdvice.content" class="empty-state">
              <el-empty description="暂无医嘱信息" />
            </div>

            <div v-else class="advice-content">
              <div class="advice-header">
                <div class="advice-meta">
                  <span class="meta-item">
                    <el-icon><Clock /></el-icon>
                    创建时间：{{ currentRecord.medicalAdvice.createTime }}
                  </span>
                  <span class="meta-item">
                    <el-icon><User /></el-icon>
                    创建医生：{{ currentRecord.medicalAdvice.doctorName }}
                  </span>
                  <span class="meta-item">
                    <el-tag
                        :type="
                        currentRecord.medicalAdvice.status === 'pending' ? 'warning' :
                        currentRecord.medicalAdvice.status === 'executed' ? 'success' : 'danger'
                      "
                    >
                      {{
                        currentRecord.medicalAdvice.status === 'pending' ? '未执行' :
                            currentRecord.medicalAdvice.status === 'executed' ? '已执行' : '已过期'
                      }}
                    </el-tag>
                  </span>
                </div>

                <div class="advice-actions">
                  <el-button
                      size="small"
                      type="text"
                      @click="handleEditAdvice"
                      v-if="currentRecord.medicalAdvice.status === 'pending' && currentRecord.order_status !== 3"
                  >
                    编辑
                  </el-button>
                  <el-button
                      size="small"
                      type="success"
                      @click="handleExecuteAdvice"
                      v-if="currentRecord.medicalAdvice.status === 'pending'"
                  >
                    标记为已执行
                  </el-button>
                </div>
              </div>

              <div class="advice-body">
                <pre>{{ currentRecord.medicalAdvice.content }}</pre>
              </div>

              <div v-if="currentRecord.medicalAdvice.executionTime" class="advice-execution-info">
                <span class="execution-label">执行时间：</span>
                <span class="execution-value">{{ currentRecord.medicalAdvice.executionTime }}</span>
              </div>
            </div>
          </el-card>
        </el-tab-pane>



        <!-- 检验报告 -->
        <el-tab-pane label="检验报告" name="test-reports">
          <el-card>
            <template #header>
              <span>检验报告</span>
              <el-button
                  size="small"
                  type="text"
                  @click="showUploadReportDialog = true"
                  v-if="currentRecord.order_status !== 3"
              >
                <el-icon><Upload /></el-icon> 上传报告
              </el-button>
            </template>

            <div v-if="!currentRecord.testReports || currentRecord.testReports.length === 0" class="empty-state">
              <el-empty description="暂无检验报告" />
            </div>

            <div v-else class="test-reports-list">
              <el-timeline>
                <el-timeline-item
                    v-for="report in currentRecord.testReports"
                    :key="report.id"
                    :timestamp="report.testTime"
                    placement="top"
                >
                  <el-card>
                    <div class="report-header">
                      <div class="report-title">{{ report.reportName }}</div>
                      <div class="report-actions">
                        <el-button
                            size="small"
                            type="text"
                            @click="handleDownloadReport(report)"
                        >
                          <el-icon><Download /></el-icon> 下载
                        </el-button>
                        <el-button
                            size="small"
                            type="text"
                            text-color="#ff4d4f"
                            @click="handleDeleteReport(report.id)"
                            v-if="currentRecord.order_status !== 3"
                        >
                          删除
                        </el-button>
                      </div>
                    </div>
                    <div class="report-meta">
                      <span class="meta-item">检验类型：{{ report.testType }}</span>
                      <span class="meta-item">检验医生：{{ report.testDoctor }}</span>
                      <span class="meta-item">检验时间：{{ formatDateTime(report.testTime) }}</span>
                      <span class="meta-item">报告时间：{{ formatDateTime(report.reportTime) }}</span>
                    </div>
                    <div class="report-summary">
                      <span class="summary-label">检验结论：</span>
                      <span class="summary-content">{{ report.conclusion || '无结论' }}</span>
                    </div>
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </div>
          </el-card>
        </el-tab-pane>

        <!-- 费用信息 -->
        <el-tab-pane label="费用信息" name="expenses">
          <el-card>
            <template #header>费用明细</template>
            <el-table
                :data="currentRecord.expenses || []"
                border
                style="width: 100%"
                v-loading="expensesLoading"
            >
              <el-table-column prop="id" label="序号" width="80" />
              <el-table-column prop="itemName" label="费用项目" />
              <el-table-column prop="category" label="类别" />
              <el-table-column prop="amount" label="金额(元)" />
              <el-table-column prop="status" label="支付状态">
                <template #default="scope">
                  <el-tag :type="scope.row.status === 'paid' ? 'success' : 'warning'">
                    {{ scope.row.status === 'paid' ? '已支付' : '未支付' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="payTime" label="支付时间">
                <template #default="scope">
                  {{ scope.row.payTime ? formatDateTime(scope.row.payTime) : '-' }}
                </template>
              </el-table-column>
            </el-table>

            <div class="total-amount" v-if="currentRecord.expenses && currentRecord.expenses.length > 0">
              <span class="total-label">总费用：</span>
              <span class="total-value">
                 ¥{{ currentRecord.expenses.reduce((sum, item) => sum + item.amount, 0).toFixed(2) }}
               </span>
            </div>

            <div v-if="!currentRecord.expenses || currentRecord.expenses.length === 0" class="empty-state">
              <el-empty description="暂无费用信息" />
            </div>
          </el-card>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <el-button @click="detailDialogVisible = false">关闭</el-button>
        <el-button
            type="primary"
            @click="completeConsultation"
            v-if="currentRecord.order_status === 4"
        >
          完成就诊
        </el-button>
      </template>
    </el-dialog>

    <!-- 添加/编辑医嘱对话框 -->
    <el-dialog
        v-model="showAddAdviceDialog"
        :title="isEditingAdvice ? '编辑医嘱' : '添加医嘱'"
        :width="600"
        @close="handleAdviceDialogClose"
    >
      <el-form ref="adviceFormRef" :model="adviceForm" label-width="80px">
        <el-form-item label="医嘱内容：" required>
          <el-input
              v-model="adviceForm.content"
              type="textarea"
              rows="6"
              placeholder="请输入医嘱内容..."
              :key="adviceFormKey"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddAdviceDialog = false">取消</el-button>
        <el-button type="primary" @click="saveAdvice">保存</el-button>
      </template>
    </el-dialog>



    <!-- 上传检验报告对话框 -->
    <el-dialog
        v-model="showUploadReportDialog"
        title="上传检验报告"
        :width="600"
    >
      <el-form ref="reportForm" :model="reportForm" label-width="100px">
        <el-form-item label="报告名称：" required>
          <el-input v-model="reportForm.reportName" placeholder="请输入报告名称" />
        </el-form-item>
        <el-form-item label="检验类型：" required>
          <el-select v-model="reportForm.testType" placeholder="请选择检验类型">
            <el-option label="血常规" value="blood" />
            <el-option label="尿常规" value="urine" />
            <el-option label="生化检查" value="biochemical" />
            <el-option label="影像学检查" value="imaging" />
            <el-option label="其他检查" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="检验时间：" required>
          <el-date-picker
              v-model="reportForm.testTime"
              type="datetime"
              placeholder="选择检验时间"
          />
        </el-form-item>
        <el-form-item label="检验医生：" required>
          <el-input v-model="reportForm.testDoctor" placeholder="请输入检验医生姓名" />
        </el-form-item>
        <el-form-item label="检验结论：">
          <el-input
              v-model="reportForm.conclusion"
              type="textarea"
              rows="3"
              placeholder="请输入检验结论..."
          />
        </el-form-item>
        <el-form-item label="报告文件：">
          <el-upload
              class="upload-demo"
              action="#"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :file-list="fileList"
              :auto-upload="false"
          >
            <el-button type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                支持上传 PDF、JPG、PNG 格式文件，最大不超过 10MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showUploadReportDialog = false">取消</el-button>
        <el-button type="primary" @click="saveTestReport">保存报告</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, nextTick, watch } from 'vue';
import { User, Clock, Upload, Download, Search } from '@element-plus/icons-vue';
import axiosInstance from '../axios/axiosInstance.js';
import { ElMessage } from 'element-plus';

// 状态管理
const status = ref('');
const department = ref('');
const dateRange = ref([]);
const searchKey = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const loading = ref(false);
const total = ref(0);

// 就诊记录列表数据
const consultationRecords = ref([]);

// 科室数据
const departmentList = ref([]);

// 对话框状态
const detailDialogVisible = ref(false);
const showAddAdviceDialog = ref(false);
const showUploadReportDialog = ref(false);
const currentRecord = ref({});
const activeTab = ref('visit-info');
const editDiagnosis = ref(false);
const diagnosisFormRef = ref(null);
const adviceFormRef = ref(null);
const isEditingAdvice = ref(false);
const adviceFormKey = ref(0);
const fileList = ref([]);
const expensesLoading = ref(false);

// 表单数据
const diagnosisForm = reactive({
  chiefComplaint: '',
  presentIllness: '',
  physicalExam: '',
  auxiliaryExam: '',
  diagnosis: '',
  treatmentPlan: ''
});

const adviceForm = reactive({
  content: ''
});

const reportForm = reactive({
  reportName: '',
  testType: '',
  testTime: '',
  testDoctor: '',
  conclusion: ''
});

// 获取科室列表
const fetchDepartments = async () => {
  try {
    const response = await axiosInstance.get('/api/v1/departments');

    if (response.data && response.data.data) {
      departmentList.value = response.data.data;
    } else {
      departmentList.value = [];
    }
  } catch (error) {
    console.error('获取科室列表失败:', error);
    departmentList.value = [];
  }
};

// 获取就诊记录列表
const fetchConsultationList = async () => {
  loading.value = true;
  try {
    const params = {
      status: status.value ? mapStatusToBackend(status.value) : '1,3,4', // 默认获取状态为1,3,4的记录
      deptName: department.value || undefined,
      searchKey: searchKey.value || undefined,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    };

    // 添加日期范围参数
    if (dateRange.value && dateRange.value.length === 2) {
      const startDate = new Date(dateRange.value[0]);
      const endDate = new Date(dateRange.value[1]);
      params.startDate = startDate.toISOString().split('T')[0];
      params.endDate = endDate.toISOString().split('T')[0];
    }

    const response = await axiosInstance.get('/api/v1/registrationList', { params });

    if (response.data && response.data.list) {
      // 转换数据格式以适配现有页面，并获取患者详细信息和诊断结果
      const recordsWithPatientDetails = await Promise.all(
          response.data.list.map(async (item) => {
            let patientDetails = {
              gender: '未知',
              age: '未知'
            };

            // 获取患者详细信息
            try {
              const patientResponse = await axiosInstance.get(`/api/v1/patient/${item.patient_id}`);
              if (patientResponse.data && patientResponse.data.data) {
                const patient = patientResponse.data.data;
                patientDetails = {
                  gender: patient.gender === 1 ? '男' : '女',
                  age: calculateAge(patient.birth_date)
                };
              }
            } catch (error) {
              console.error(`获取患者${item.patient_id}详情失败:`, error);
            }

            // 获取诊断结果
            let diagnosis = '暂无诊断';
            try {
              const recordResponse = await axiosInstance.get('/api/v1/get-by-order', {
                params: { orderId: item.order_id }
              });
              if (recordResponse.data && recordResponse.data.data) {
                diagnosis = recordResponse.data.data.diagnosis || '暂无诊断';
              }
            } catch (error) {
              console.error(`获取订单${item.order_id}诊断信息失败:`, error);
            }

            return {
              id: item.order_id,
              patientName: item.patient_name,
              gender: patientDetails.gender,
              age: patientDetails.age,
              registrationNo: item.order_no,
              department: item.dept_name,
              visitTime: formatDateTime(item.visit_time || item.create_time),
              doctorName: item.doctor_name,
              diagnosis: diagnosis,
              status: mapStatus(item.order_status),
              order_status: item.order_status, // 添加原始状态值
              patientId: item.patient_id,
              orderId: item.order_id,
              symptoms: item.symptoms,
              amount: item.amount,
              visit_no: item.visit_no,
              dept_name: item.dept_name,
              visit_time: item.visit_time,
              doctor_id: item.doctor_id,
              doctor_name: item.doctor_name,
              // 添加所有后端返回的字段
              pay_status: item.pay_status,
              pay_time: item.pay_time,
              cancel_time: item.cancel_time,
              create_time: item.create_time,
              update_time: item.update_time,
              user_id: item.user_id,
              dept_id: item.dept_id,
              schedule_id: item.schedule_id,
              visit_date: item.visit_date,
              time_slot: item.time_slot
            };
          })
      );

      consultationRecords.value = recordsWithPatientDetails;
      total.value = response.data.total || response.data.list.length;
    } else {
      consultationRecords.value = [];
      total.value = 0;
    }
  } catch (error) {
    console.error('获取就诊记录列表失败:', error);
    ElMessage.error('获取就诊记录列表失败');
    consultationRecords.value = [];
    total.value = 0;
  } finally {
    loading.value = false;
  }
};

// 计算年龄
const calculateAge = (birthDate) => {
  if (!birthDate) return '未知';
  try {
    const birth = new Date(birthDate);
    const today = new Date();
    const age = today.getFullYear() - birth.getFullYear();
    const monthDiff = today.getMonth() - birth.getMonth();
    return monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate()) ? age - 1 : age;
  } catch (error) {
    return '未知';
  }
};

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  try {
    const date = new Date(dateTimeStr);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    });
  } catch (error) {
    return dateTimeStr;
  }
};

// 映射状态
const mapStatus = (orderStatus) => {
  // 确保转换为数字进行比较
  const status = parseInt(orderStatus);
  switch (status) {
    case 1: return 'pending'; // 待就诊
    case 3: return 'completed'; // 已完成
    case 4: return 'processing'; // 就诊中
    default: return 'pending'; // 默认为待就诊
  }
};

// 反向映射状态（用于发送到后端）
const mapStatusToBackend = (status) => {
  if (!status) return '';
  switch (status) {
    case 'pending': return '1';
    case 'processing': return '4';
    case 'completed': return '3';
    default: return '';
  }
};



// 模拟就诊记录数据（保留作为备用）
const mockConsultationRecords = ref([
  {
    id: 1,
    patientName: '张三',
    gender: '男',
    age: 35,
    birthDate: '1988-05-12',
    patientId: 'PT20230512001',
    phone: '13800138000',
    idCard: '110101198805121234',
    registrationNo: 'REG20230512001',
    department: 'internal',
    doctorName: '张医生',
    visitTime: '2023-05-12 09:30',
    symptoms: '头痛、发热、乏力',
    temperature: 38.5,
    bloodPressure: '120/80 mmHg',
    heartRate: 78,
    visitType: 'first',
    status: 'processing',
    consultInfo: {
      chiefComplaint: '头痛伴发热2天',
      presentIllness: '患者2天前无明显诱因出现头痛，体温最高38.5℃，伴乏力、肌肉酸痛，无咳嗽咳痰，无腹痛腹泻。',
      pastHistory: '既往体健，否认高血压、糖尿病等慢性病史，否认手术外伤史，否认药物过敏史。',
      examinationResult: '血常规：白细胞 12.5×10^9/L，中性粒细胞百分比 85%，淋巴细胞百分比 12%。',
      diagnosis: '上呼吸道感染'
    },
    medicalAdvice: {
      id: 1,
      content: '1. 布洛芬缓释胶囊 0.3g 口服 每日2次 连续3天；\n2. 多饮水，每日饮水量不少于2000ml；\n3. 注意休息，避免劳累；\n4. 清淡饮食，避免辛辣刺激性食物；\n5. 如体温持续超过39℃或症状加重，请及时复诊。',
      createTime: '2023-05-12 10:15',
      doctorName: '张医生',
      status: 'pending'
    },

    testReports: [
      {
        id: 1,
        reportName: '血常规检查',
        testType: 'blood',
        testTime: '2023-05-12 09:45',
        testDoctor: '李医生',
        conclusion: '白细胞及中性粒细胞百分比升高，提示细菌感染',
        fileUrl: '/reports/blood-20230512001.pdf'
      }
    ],
    expenses: [
      { id: 1, itemName: '门诊挂号费', category: '诊疗费', amount: 15, status: 'paid', payTime: '2023-05-12 09:00' },
      { id: 2, itemName: '血常规检查', category: '检查费', amount: 35, status: 'paid', payTime: '2023-05-12 09:40' },
      { id: 3, itemName: '布洛芬缓释胶囊', category: '药品费', amount: 28.5, status: 'unpaid' },
      { id: 4, itemName: '维生素C片', category: '药品费', amount: 12.8, status: 'unpaid' }
    ]
  },
  {
    id: 2,
    patientName: '李四',
    gender: '女',
    age: 28,
    birthDate: '1995-03-20',
    patientId: 'PT20230512002',
    phone: '13900139000',
    idCard: '310101199503204567',
    registrationNo: 'REG20230512002',
    department: 'obstetrics',
    doctorName: '王医生',
    visitTime: '2023-05-12 10:15',
    symptoms: '孕期常规检查',
    temperature: 36.5,
    bloodPressure: '115/75 mmHg',
    heartRate: 72,
    visitType: 'followup',
    status: 'completed',
    consultInfo: {
      chiefComplaint: '孕20周常规产检',
      presentIllness: '孕妇目前孕20周，无腹痛、阴道出血等不适，胎动正常。',
      pastHistory: '否认高血压、糖尿病等慢性病史，否认手术外伤史。',
      examinationResult: 'B超检查：胎儿发育正常，胎心145次/分，羊水适量。',
      diagnosis: '孕20周，单活胎'
    },
    medicalAdvice: {
      id: 2,
      content: '1. 注意休息，避免劳累；\n2. 均衡饮食，补充钙剂和铁剂；\n3. 适当运动，如散步；\n4. 保持心情舒畅；\n5. 孕24-28周行糖耐量检查；\n6. 定期产检，每4周一次。',
      createTime: '2023-05-12 11:00',
      doctorName: '王医生',
      status: 'executed',
      executionTime: '2023-05-12 11:30'
    },

    testReports: [
      {
        id: 2,
        reportName: '产科B超检查',
        testType: 'imaging',
        testTime: '2023-05-12 10:30',
        testDoctor: '赵医生',
        conclusion: '胎儿发育正常，符合孕周',
        fileUrl: '/reports/ultrasound-20230512002.pdf'
      }
    ],
    expenses: [
      { id: 1, itemName: '产科挂号费', category: '诊疗费', amount: 20, status: 'paid', payTime: '2023-05-12 09:30' },
      { id: 2, itemName: '产科B超', category: '检查费', amount: 180, status: 'paid', payTime: '2023-05-12 10:20' },
      { id: 3, itemName: '复方碳酸钙咀嚼片', category: '药品费', amount: 58.5, status: 'paid', payTime: '2023-05-12 14:20' },
      { id: 4, itemName: '富马酸亚铁颗粒', category: '药品费', amount: 32.8, status: 'paid', payTime: '2023-05-12 14:20' }
    ]
  },
  {
    id: 3,
    patientName: '王五',
    gender: '男',
    age: 45,
    birthDate: '1978-08-05',
    patientId: 'PT20230511005',
    phone: '13700137000',
    idCard: '440101197808057890',
    registrationNo: 'REG20230511005',
    department: 'internal',
    doctorName: '李医生',
    visitTime: '2023-05-11 15:40',
    symptoms: '头晕、血压升高',
    temperature: 36.3,
    bloodPressure: '150/95 mmHg',
    heartRate: 82,
    visitType: 'followup',
    status: 'completed',
    consultInfo: {
      chiefComplaint: '高血压病史3年，头晕1周',
      presentIllness: '患者有高血压病史3年，近1周出现头晕不适，自测血压150/95mmHg，目前服用硝苯地平控释片。',
      pastHistory: '高血压病史3年，否认糖尿病等其他慢性病史。',
      examinationResult: '血压150/95mmHg，心率82次/分，心电图未见明显异常。',
      diagnosis: '高血压2级'
    },
    medicalAdvice: {
      id: 3,
      content: '1. 继续服用硝苯地平控释片；\n2. 建议加用缬沙坦胶囊；\n3. 每日监测血压并记录；\n4. 低盐低脂饮食；\n5. 适当运动，控制体重；\n6. 1个月后复诊。',
      createTime: '2023-05-11 16:20',
      doctorName: '李医生',
      status: 'executed',
      executionTime: '2023-05-11 16:40'
    },

    testReports: [
      {
        id: 3,
        reportName: '心电图检查',
        testType: 'other',
        testTime: '2023-05-11 16:00',
        testDoctor: '孙医生',
        conclusion: '窦性心律，大致正常心电图',
        fileUrl: '/reports/ecg-20230511005.pdf'
      }
    ],
    expenses: [
      { id: 1, itemName: '内科挂号费', category: '诊疗费', amount: 15, status: 'paid', payTime: '2023-05-11 15:00' },
      { id: 2, itemName: '心电图检查', category: '检查费', amount: 30, status: 'paid', payTime: '2023-05-11 15:50' },
      { id: 3, itemName: '硝苯地平控释片', category: '药品费', amount: 48.5, status: 'paid', payTime: '2023-05-11 17:00' },
      { id: 4, itemName: '缬沙坦胶囊', category: '药品费', amount: 65.2, status: 'paid', payTime: '2023-05-11 17:00' }
    ]
  }
]);

// 过滤后的记录列表（现在主要依赖后端筛选，这里保留基本的前端筛选逻辑）
const filteredRecords = computed(() => {
  return consultationRecords.value.filter(record => {
    // 关键词搜索（前端筛选）
    if (searchKey.value) {
      const searchLower = searchKey.value.toLowerCase();
      if (
          !record.patientName.toLowerCase().includes(searchLower) &&
          !record.registrationNo.toLowerCase().includes(searchLower) &&
          !record.diagnosis.toLowerCase().includes(searchLower)
      ) {
        return false;
      }
    }
    return true;
  });
});

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1;
  fetchConsultationList();
};

// 重置筛选条件
const resetFilter = () => {
  status.value = '';
  department.value = '';
  dateRange.value = [];
  searchKey.value = '';
  currentPage.value = 1;
  fetchConsultationList();
};

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 重置到第一页
  fetchConsultationList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchConsultationList();
};

// 行点击事件
const handleRowClick = (row) => {
  handleViewDetails(row);
};

// 查看详情
const handleViewDetails = async (row) => {
  try {
    // 获取患者详细信息
    let patientDetails = {};
    try {
      const patientResponse = await axiosInstance.get(`/api/v1/patient/${row.patientId}`);
      if (patientResponse.data && patientResponse.data.data) {
        patientDetails = patientResponse.data.data;
      }
    } catch (error) {
      console.error(`获取患者${row.patientId}详情失败:`, error);
    }

    // 获取就诊记录详情
    const recordResponse = await axiosInstance.get('/api/v1/get-by-order', {
      params: { orderId: row.orderId }
    });

    // 获取检验报告列表
    let testReports = [];
    try {
      const reportResponse = await axiosInstance.get('/api/v1/report', {
        params: { patientId: row.patientId }
      });
      if (reportResponse.data && reportResponse.data.code === 0 && reportResponse.data.data) {
        testReports = reportResponse.data.data.map(report => ({
          id: report.report_id,
          reportName: report.name,
          testType: report.type,
          testTime: report.check_time,
          reportTime: report.report_time,
          testDoctor: report.username,
          conclusion: report.content,
          fileUrl: report.report_url,
          status: report.status,
          createTime: report.create_time,
          updateTime: report.update_time
        }));
      }
    } catch (error) {
      console.error(`获取患者${row.patientId}检验报告失败:`, error);
    }

    // 获取费用信息
    let expenses = [];
    try {
      expenses = await fetchExpenses(row.patientId);
    } catch (error) {
      console.error(`获取患者${row.patientId}费用信息失败:`, error);
    }

    if (recordResponse.data && recordResponse.data.data) {
      // 合并患者基本信息和就诊记录
      const fullRecordData = {
        ...row,
        ...patientDetails, // 添加患者详细信息
        medicalRecord: recordResponse.data.data,
        testReports: testReports, // 添加检验报告
        expenses: expenses, // 添加费用信息
        // 添加医嘱信息
        medicalAdvice: {
          content: recordResponse.data.data.advice || '',
          createTime: recordResponse.data.data.create_time || '',
          doctorName: row.doctor_name || '',
          status: 'pending'
        }
      };

      currentRecord.value = fullRecordData;

      // 初始化诊断表单
      if (diagnosisForm) {
        Object.assign(diagnosisForm, {
          chiefComplaint: recordResponse.data.data.chief_complaint || '',
          presentIllness: recordResponse.data.data.present_illness || '',
          physicalExam: recordResponse.data.data.physical_exam || '',
          auxiliaryExam: recordResponse.data.data.auxiliary_exam || '',
          diagnosis: recordResponse.data.data.diagnosis || '',
          treatmentPlan: recordResponse.data.data.treatment_plan || ''
        });
      }
    } else {
      // 如果没有就诊记录，只显示基本信息
      currentRecord.value = {
        ...row,
        ...patientDetails,
        testReports: testReports, // 添加检验报告
        expenses: expenses // 添加费用信息
      };
      if (diagnosisForm) {
        Object.assign(diagnosisForm, row.consultInfo || {});
      }
    }

    detailDialogVisible.value = true;
    activeTab.value = 'visit-info';
    editDiagnosis.value = false;
  } catch (error) {
    console.error('获取就诊记录详情失败:', error);
    currentRecord.value = row;
    if (diagnosisForm) {
      Object.assign(diagnosisForm, row.consultInfo || {});
    }
    detailDialogVisible.value = true;
    activeTab.value = 'visit-info';
    editDiagnosis.value = false;
  }
};

// 编辑记录
const handleEditRecord = (row) => {
  handleViewDetails(row);
  // 可以跳转到编辑页面或在当前弹窗中开启编辑模式
};

// 获取检验报告列表
const fetchTestReports = async (patientId) => {
  try {
    const response = await axiosInstance.get('/api/v1/report', {
      params: { patientId: patientId }
    });

    if (response.data && response.data.code === 0 && response.data.data) {
      return response.data.data.map(report => ({
        id: report.report_id,
        reportName: report.name,
        testType: report.type,
        testTime: report.check_time,
        reportTime: report.report_time,
        testDoctor: report.username,
        conclusion: report.content,
        fileUrl: report.report_url,
        status: report.status,
        createTime: report.create_time,
        updateTime: report.update_time
      }));
    }
    return [];
  } catch (error) {
    console.error(`获取患者${patientId}检验报告失败:`, error);
    return [];
  }
};

// 获取费用信息
const fetchExpenses = async (patientId) => {
  try {
    expensesLoading.value = true;
    const response = await axiosInstance.get(`/api/v1/payment/record/${patientId}`);

    if (response.data && response.data.code === 0 && response.data.data) {
      return response.data.data.map(expense => ({
        id: expense.record_id,
        itemName: '挂号费', // 根据后端数据，这里显示为挂号费
        category: '挂号', // 根据后端数据，这里显示为挂号类别
        amount: expense.amount,
        status: expense.status === 1 ? 'paid' : 'unpaid',
        payTime: expense.pay_time
      }));
    }
    return [];
  } catch (error) {
    console.error(`获取患者${patientId}费用信息失败:`, error);
    ElMessage.error('获取费用信息失败');
    return [];
  } finally {
    expensesLoading.value = false;
  }
};

// 编辑病情诊断
const handleEditDiagnosis = () => {
  // 确保表单对象存在
  if (!diagnosisForm) {
    console.error('diagnosisForm is null');
    return;
  }

  // 从后端数据填充表单
  if (currentRecord.value.medicalRecord) {
    diagnosisForm.chiefComplaint = currentRecord.value.medicalRecord.chief_complaint || '';
    diagnosisForm.presentIllness = currentRecord.value.medicalRecord.present_illness || '';
    diagnosisForm.physicalExam = currentRecord.value.medicalRecord.physical_exam || '';
    diagnosisForm.auxiliaryExam = currentRecord.value.medicalRecord.auxiliary_exam || '';
    diagnosisForm.diagnosis = currentRecord.value.medicalRecord.diagnosis || '';
    diagnosisForm.treatmentPlan = currentRecord.value.medicalRecord.treatment_plan || '';
  }
  editDiagnosis.value = true;
};

// 关闭详情对话框
const handleDialogClose = () => {
  detailDialogVisible.value = false;
};

// 关闭医嘱对话框
const handleAdviceDialogClose = () => {
  adviceForm.content = '';
  isEditingAdvice.value = false;
  adviceFormKey.value++;
};

// 保存诊断信息
const saveDiagnosis = async () => {
  try {
    // 确保表单对象存在
    if (!diagnosisForm) {
      ElMessage.error('表单数据异常，请重试');
      return;
    }

    // 检查是否有record_id，如果没有则创建新记录
    let recordId = currentRecord.value.medicalRecord?.record_id;

    const consultationData = {
      patient_id: currentRecord.value.patientId,
      doctor_id: currentRecord.value.doctor_id || 1,
      order_id: currentRecord.value.orderId,
      visit_date: new Date().toISOString().split('T')[0],
      chief_complaint: diagnosisForm.chiefComplaint || '',
      present_illness: diagnosisForm.presentIllness || '',
      physical_exam: diagnosisForm.physicalExam || '',
      auxiliary_exam: diagnosisForm.auxiliaryExam || '',
      diagnosis: diagnosisForm.diagnosis || '',
      treatment_plan: diagnosisForm.treatmentPlan || '',
      prescription: currentRecord.value.medicalRecord?.prescription || '',
      advice: currentRecord.value.medicalRecord?.advice || '',
      next_visit_date: currentRecord.value.medicalRecord?.next_visit_date || new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
      status: 1
    };

    // 如果有record_id，添加到请求数据中
    if (recordId) {
      consultationData.record_id = recordId;
    }

    const response = await axiosInstance.post('/api/v1/update', consultationData);

    if (response.data && response.data.code === '0') {
      ElMessage.success('诊断信息保存成功');

      // 更新本地数据
      if (currentRecord.value.medicalRecord) {
        currentRecord.value.medicalRecord.chief_complaint = diagnosisForm.chiefComplaint || '';
        currentRecord.value.medicalRecord.present_illness = diagnosisForm.presentIllness || '';
        currentRecord.value.medicalRecord.physical_exam = diagnosisForm.physicalExam || '';
        currentRecord.value.medicalRecord.auxiliary_exam = diagnosisForm.auxiliaryExam || '';
        currentRecord.value.medicalRecord.diagnosis = diagnosisForm.diagnosis || '';
        currentRecord.value.medicalRecord.treatment_plan = diagnosisForm.treatmentPlan || '';

        // 如果返回了新的record_id，更新它
        if (response.data.data && response.data.data.record_id) {
          currentRecord.value.medicalRecord.record_id = response.data.data.record_id;
        }
      }

      // 保持原有的order_status不变
      // 保存诊断信息不应该改变订单状态

      // 更新列表中的数据，但保持原有的order_status不变
      const index = consultationRecords.value.findIndex(item => item.id === currentRecord.value.id);
      if (index !== -1) {
        // 只更新诊断相关的字段，保持原有的order_status
        consultationRecords.value[index].medicalRecord = { ...currentRecord.value.medicalRecord };
        // 确保order_status不被覆盖
        consultationRecords.value[index].order_status = currentRecord.value.order_status;
        // 确保status字段也正确更新（基于order_status）
        consultationRecords.value[index].status = mapStatus(currentRecord.value.order_status);
      }

      editDiagnosis.value = false;
    } else {
      ElMessage.error('保存诊断信息失败');
    }
  } catch (error) {
    console.error('保存诊断信息失败:', error);
    ElMessage.error('保存诊断信息失败');
  }
};

// 编辑医嘱
const handleEditAdvice = () => {
  if (currentRecord.value.medicalAdvice) {
    adviceForm.content = currentRecord.value.medicalAdvice.content || '';
    isEditingAdvice.value = true;
    adviceFormKey.value++; // 强制重新渲染输入框
    showAddAdviceDialog.value = true;
  }
};

// 保存医嘱
const saveAdvice = async () => {
  try {
    // 需要先获取record_id，如果没有则提示用户先保存就诊记录
    if (!currentRecord.value.medicalRecord || !currentRecord.value.medicalRecord.record_id) {
      ElMessage.warning('请先保存就诊记录，再保存医嘱');
      return;
    }

    const params = {
      record_id: currentRecord.value.medicalRecord.record_id,
      advice: adviceForm.content
    };

    const response = await axiosInstance.post('/api/v1/saveAdvice', null, { params });

    if (response.data && response.data.code === '0') {
      ElMessage.success('医嘱保存成功');

      // 更新本地数据
      if (isEditingAdvice.value) {
        // 编辑现有医嘱
        currentRecord.value.medicalAdvice.content = adviceForm.content;
      } else {
        // 添加新医嘱
        const newAdvice = {
          id: Date.now(),
          content: adviceForm.content,
          createTime: new Date().toLocaleString(),
          doctorName: currentRecord.value.doctorName,
          status: 'pending'
        };
        currentRecord.value.medicalAdvice = newAdvice;
      }

      // 更新列表中的数据
      const index = consultationRecords.value.findIndex(item => item.id === currentRecord.value.id);
      if (index !== -1) {
        consultationRecords.value[index] = { ...currentRecord.value };
      }

      showAddAdviceDialog.value = false;
      adviceForm.content = '';
      isEditingAdvice.value = false;
      adviceFormKey.value++;
    } else {
      ElMessage.error('医嘱保存失败');
    }
  } catch (error) {
    console.error('医嘱保存失败:', error);
    ElMessage.error('医嘱保存失败');
  }
};

// 标记医嘱为已执行
const handleExecuteAdvice = () => {
  if (currentRecord.value.medicalAdvice) {
    currentRecord.value.medicalAdvice.status = 'executed';
    currentRecord.value.medicalAdvice.executionTime = new Date().toLocaleString();

    // 模拟API请求
    axios.post(`/api/medical-advice/${currentRecord.value.medicalAdvice.id}/execute`, {
      executionTime: currentRecord.value.medicalAdvice.executionTime
    }).then(response => {
      console.log('医嘱标记为已执行', response.data);
    }).catch(error => {
      console.error('操作失败', error);
    });

    // 更新原数据
    const index = consultationRecords.value.findIndex(item => item.id === currentRecord.value.id);
    if (index !== -1) {
      consultationRecords.value[index] = { ...currentRecord.value };
    }
  }
};



// 保存检验报告
const saveTestReport = () => {
  if (!currentRecord.value.testReports) {
    currentRecord.value.testReports = [];
  }

  const newReport = {
    id: Date.now(),
    ...reportForm,
    fileUrl: '/reports/' + reportForm.reportName.replace(/\s+/g, '-') + '.pdf'
  };

  currentRecord.value.testReports.push(newReport);

  // 模拟API请求
  axios.post('/api/test-reports', {
    consultationId: currentRecord.value.id,
    ...newReport
  }).then(response => {
    console.log('检验报告保存成功', response.data);
  }).catch(error => {
    console.error('检验报告保存失败', error);
  });

  // 更新原数据
  const index = consultationRecords.value.findIndex(item => item.id === currentRecord.value.id);
  if (index !== -1) {
    consultationRecords.value[index] = { ...currentRecord.value };
  }

  showUploadReportDialog.value = false;
  // 重置表单
  Object.keys(reportForm).forEach(key => {
    reportForm[key] = '';
  });
  fileList.value = [];
};

// 处理文件预览
const handlePreview = (file) => {
  console.log('预览文件:', file);
};

// 处理文件移除
const handleRemove = (file, fileList) => {
  console.log('移除文件:', file, fileList);
};

// 下载报告
const handleDownloadReport = (report) => {
  console.log('下载报告:', report.fileUrl);
  // 实际应用中这里会触发文件下载
};

// 删除报告
const handleDeleteReport = (reportId) => {
  if (currentRecord.value.testReports) {
    currentRecord.value.testReports = currentRecord.value.testReports.filter(report => report.id !== reportId);

    // 模拟API请求
    axios.delete(`/api/test-reports/${reportId}`)
        .then(response => {
          console.log('报告删除成功', response.data);
        }).catch(error => {
      console.error('报告删除失败', error);
    });

    // 更新原数据
    const index = consultationRecords.value.findIndex(item => item.id === currentRecord.value.id);
    if (index !== -1) {
      consultationRecords.value[index] = { ...currentRecord.value };
    }
  }
};

// 完成就诊
const completeConsultation = () => {
  currentRecord.value.status = 'completed';

  // 模拟API请求
  axios.post(`/api/consultation/${currentRecord.value.id}/complete`)
      .then(response => {
        console.log('就诊标记为已完成', response.data);
      }).catch(error => {
    console.error('操作失败', error);
  });

  // 更新原数据
  const index = consultationRecords.value.findIndex(item => item.id === currentRecord.value.id);
  if (index !== -1) {
    consultationRecords.value[index] = { ...currentRecord.value };
  }
};

// 格式化科室名称
const formatDepartment = (deptCode) => {
  const deptMap = {
    'internal': '内科',
    'surgery': '外科',
    'pediatrics': '儿科',
    'obstetrics': '妇产科',
    'dermatology': '皮肤科'
  };
  return deptMap[deptCode] || deptCode;
};

// 身份证号掩码处理
const maskIdCard = (idCard) => {
  if (!idCard || idCard.length !== 18) return idCard;
  return idCard.replace(/^(\d{6})\d{8}(\d{4})$/, '$1********$2');
};

// 表格行样式
const tableRowClassName = ({ row }) => {
  if (row.status === 'processing') {
    return 'processing-row';
  }
  return '';
};

// 监听标签页切换，当切换到检验报告或费用信息时获取最新数据
watch(activeTab, async (newTab) => {
  if (newTab === 'test-reports' && currentRecord.value.patientId) {
    try {
      const reports = await fetchTestReports(currentRecord.value.patientId);
      currentRecord.value.testReports = reports;
    } catch (error) {
      console.error('获取检验报告失败:', error);
    }
  }

  if (newTab === 'expenses' && currentRecord.value.patientId) {
    try {
      const expenses = await fetchExpenses(currentRecord.value.patientId);
      currentRecord.value.expenses = expenses;
    } catch (error) {
      console.error('获取费用信息失败:', error);
    }
  }
});

// 页面加载时获取数据
onMounted(async () => {
  // 先获取科室数据，再获取就诊记录列表
  await fetchDepartments();
  await fetchConsultationList();
});
</script>

<style scoped>
.consultation-record-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #1e293b;
  margin: 0;
}

.filter-card {
  margin-bottom: 20px;
  padding: 15px;
}

.record-list-card {
  padding: 0;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
  padding: 15px;
}

/* 表格行样式 */
:deep(.processing-row) {
  background-color: #fffbeb !important;
}

/* 详情弹窗样式 */
.patient-basic-card {
  margin-bottom: 20px;
}

.patient-avatar-container {
  display: flex;
  align-items: flex-start;
}

.patient-avatar {
  position: relative;
  margin-right: 20px;
}

.patient-tag {
  position: absolute;
  top: -5px;
  right: -5px;
}

.patient-main-info {
  flex: 1;
}

.name-and-id {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.patient-name {
  font-size: 18px;
  font-weight: 600;
  margin-right: 15px;
}

.patient-id {
  color: #64748b;
  font-size: 14px;
}

.patient-basic-details {
  display: flex;
  flex-wrap: wrap;
  gap: 15px 30px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-label {
  color: #64748b;
  width: 90px;
}

.detail-value {
  flex-grow: 1;
  font-weight: 500;
}

.detail-tabs {
  margin-top: 20px;
}

.mt-4 {
  margin-top: 16px !important;
}

/* 就诊信息样式 */
.visit-info-item {
  margin-bottom: 12px;
}

.info-label {
  color: #64748b;
  display: inline-block;
  width: 100px;
}

.info-value {
  font-weight: 500;
}

.form-actions {
  margin-top: 15px;
  text-align: right;
}

/* 医嘱样式 */
.empty-state {
  padding: 40px 0;
  text-align: center;
}

.advice-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e2e8f0;
}

.advice-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.meta-item {
  display: flex;
  align-items: center;
  color: #64748b;
  font-size: 14px;
}

.meta-item .el-icon {
  margin-right: 5px;
  font-size: 14px;
}

.advice-actions {
  display: flex;
  gap: 10px;
}

.advice-body {
  padding: 15px;
  background-color: #f8fafc;
  border-radius: 4px;
  margin-bottom: 15px;
  white-space: pre-line;
  line-height: 1.6;
}

.advice-execution-info {
  color: #64748b;
  font-size: 14px;
  padding-top: 10px;
  border-top: 1px dashed #e2e8f0;
}

.execution-label {
  font-weight: 500;
  margin-right: 5px;
}



/* 检验报告样式 */
.test-reports-list {
  margin-top: 10px;
}

:deep(.el-timeline) {
  padding-left: 20px;
}

:deep(.el-timeline-item__timestamp) {
  font-size: 13px;
  color: #64748b;
  margin-bottom: 8px;
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.report-title {
  font-weight: 600;
  color: #1e293b;
}

.report-actions {
  display: flex;
  gap: 5px;
}

.report-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 10px;
  color: #64748b;
  font-size: 14px;
}

.report-summary {
  margin-top: 10px;
  line-height: 1.6;
}

.summary-label {
  font-weight: 500;
  display: block;
  margin-bottom: 5px;
}

/* 费用信息样式 */
.total-amount {
  margin-top: 15px;
  text-align: right;
  font-size: 16px;
}

.total-label {
  color: #64748b;
  margin-right: 5px;
}

.total-value {
  font-weight: 600;
  color: #1e293b;
}



/* 病情诊断显示样式 */
.diagnosis-display {
  padding: 15px;
  background-color: #f8fafc;
  border-radius: 4px;
  border: 1px solid #e2e8f0;
}

.diagnosis-item {
  margin-bottom: 15px;
}

.diagnosis-item:last-child {
  margin-bottom: 0;
}

.diagnosis-label {
  display: block;
  font-weight: 600;
  color: #374151;
  margin-bottom: 5px;
  font-size: 14px;
}

.diagnosis-content {
  padding: 10px;
  background-color: #ffffff;
  border: 1px solid #d1d5db;
  border-radius: 4px;
  min-height: 20px;
  line-height: 1.5;
  color: #1f2937;
  white-space: pre-line;
}
</style>
